#!/bin/bash
EXPENSES_FILE="main_data_A5.txt"
TEMP_FILE="expenses_temp_A5.csv"
if [ ! -f "$EXPENSES_FILE" ]; then
    echo "错误: 数据文件 '$EXPENSES_FILE' 不存在。"
    echo "请先运行 'import_data_A5.sh' 脚本导入初始数据。"
    exit 1
fi
IFS=',' read -r -a HEADERS < <(head -n 1 "$EXPENSES_FILE")
TIME_COL_NUM=-1
AMOUNT_COL_NUM=-1
MAIN_CAT_COL_NUM=-1
REMARKS_COL_NUM=-1
for i in "${!HEADERS[@]}"; do
    case "${HEADERS[$i]}" in
        "时间") TIME_COL_NUM=$((i + 1)) ;;
        "金额") AMOUNT_COL_NUM=$((i + 1)) ;;
        "大分类") MAIN_CAT_COL_NUM=$((i + 1)) ;;
        "备注") REMARKS_COL_NUM=$((i + 1)) ;;
    esac
done
if [ "$TIME_COL_NUM" -eq -1 ] || [ "$AMOUNT_COL_NUM" -eq -1 ] || [ "$MAIN_CAT_COL_NUM" -eq -1 ]; then
    echo "错误：CSV文件中未能找到核心的'时间'或'金额'或'大分类'列。"
    exit 1
fi
add_expense_info() {
    echo "--- 添加新的消费记录 ---"
    local new_record_array=()
    local input_value
    for i in "${!HEADERS[@]}"; do
        if (( (i + 1) == TIME_COL_NUM )); then
            read -p "请输入 '${HEADERS[$i]}' (格式YYYY/M/D 或 YYYY/MM/DD): " input_value
            if ! [[ "$input_value" =~ ^[0-9]{4}/([1-9]|0[1-9]|1[0-2])/([1-9]|0[1-9]|[12][0-9]|3[01])$ ]]; then
                echo "日期格式不正确。操作取消。"
                return
            fi
        elif (( (i + 1) == AMOUNT_COL_NUM )); then
             read -p "请输入 '${HEADERS[$i]}': " input_value
             if ! [[ "$input_value" =~ ^[0-9]+(\.[0-9]{1,2})?$ ]]; then
                echo "金额格式不正确。操作取消。"
                return
             fi
        else
            read -p "请输入 '${HEADERS[$i]}': " input_value
        fi
        new_record_array+=("$input_value")
    done
    new_record_line=$(IFS=,; echo "${new_record_array[*]}")
    echo "$new_record_line" >> "$EXPENSES_FILE"
    echo "消费记录添加成功！"
}
delete_expense_info() {
    echo "--- 删除消费记录 ---"
    echo "为了准确定位记录，建议先查询并记下要删除记录的“时间”、“金额”和“备注”。"
    read -p "请输入要删除记录的时间 (YYYY/M/D 或 YYYY/MM/DD): " del_time
    read -p "请输入要删除记录的金额: " del_amount
    read -p "请输入要删除记录的备注 (如果备注为空，请直接回车): " del_remarks
    local found_to_delete=0
    awk -F, -v t_col="$TIME_COL_NUM" -v a_col="$AMOUNT_COL_NUM" -v r_col="$REMARKS_COL_NUM" \
        -v dt="$del_time" -v da="$del_amount" -v dr="$del_remarks" \
        'BEGIN{OFS=","} NR==1 {print $0; next} 
        { 
            remarks_match = 1;
            if (r_col != -1) {
                 if ($r_col != dr) remarks_match = 0;
            } else if (dr != "") { 
                 remarks_match = 0; 
            }
            if ($t_col == dt && $a_col == da && remarks_match) {
                found_to_delete=1; next
            } print $0 
        }' "$EXPENSES_FILE" > "$TEMP_FILE"
    if grep -q '.' "$TEMP_FILE"; then 
      lines_original=$(wc -l < "$EXPENSES_FILE")
      lines_temp=$(wc -l < "$TEMP_FILE")
      if [ "$lines_original" -gt "$lines_temp" ]; then
        mv "$TEMP_FILE" "$EXPENSES_FILE"
        echo "匹配的消费记录已删除。"
      else
        echo "未找到完全匹配的记录进行删除，或该记录不存在。"
        rm "$TEMP_FILE"
      fi
    else
        echo "处理临时文件时发生错误或未找到记录。"
        rm -f "$TEMP_FILE"
    fi
}
modify_expense_info() {
    echo "--- 修改消费记录 ---"
    echo "为了准确定位记录，建议先查询并记下要修改记录的“时间”、“金额”和“备注”。"
    read -p "请输入要修改记录的原始时间 (YYYY/M/D 或 YYYY/MM/DD): " mod_time
    read -p "请输入要修改记录的原始金额: " mod_amount
    read -p "请输入要修改记录的原始备注 (如果备注为空，请直接回车): " mod_remarks
    local line_num_to_modify=0
    line_num_to_modify=$(awk -F, -v t_col="$TIME_COL_NUM" -v a_col="$AMOUNT_COL_NUM" -v r_col="$REMARKS_COL_NUM" \
        -v mt="$mod_time" -v ma="$mod_amount" -v mr="$mod_remarks" \
        'NR > 1 {
            remarks_match_mod = 1;
            if (r_col != -1) {
                 if ($r_col != mr) remarks_match_mod = 0;
            } else if (mr != "") {
                 remarks_match_mod = 0;
            }
            if ($t_col == mt && $a_col == ma && remarks_match_mod) {print NR; exit}
        }' "$EXPENSES_FILE")
    if [ -z "$line_num_to_modify" ] || [ "$line_num_to_modify" -eq 0 ]; then
        echo "未找到完全匹配的记录进行修改。"
        return
    fi
    echo "找到记录 (行号 $line_num_to_modify)。当前信息:"
    awk -F, -v ln="$line_num_to_modify" 'NR==ln' "$EXPENSES_FILE"
    echo "请输入新的信息 (若某项不想修改，请直接按回车键以保留原值):"
    local old_values_array
    local new_values_array=()
    local input_val
    IFS=',' read -r -a old_values_array < <(awk -F, -v ln="$line_num_to_modify" 'NR==ln {print $0}' "$EXPENSES_FILE")
    for i in "${!HEADERS[@]}"; do
        read -p "新的 '${HEADERS[$i]}' (原: ${old_values_array[$i]}): " input_val
        if [ -z "$input_val" ]; then
            new_values_array+=("${old_values_array[$i]}")
        else
            if (( (i + 1) == TIME_COL_NUM )); then
                if ! [[ "$input_val" =~ ^[0-9]{4}/([1-9]|0[1-9]|1[0-2])/([1-9]|0[1-9]|[12][0-9]|3[01])$ ]]; then
                    echo "新日期格式不正确，此字段将保留原值。操作继续。"
                    new_values_array+=("${old_values_array[$i]}")
                    continue
                fi
            elif (( (i + 1) == AMOUNT_COL_NUM )); then
                 if ! [[ "$input_val" =~ ^[0-9]+(\.[0-9]{1,2})?$ ]]; then
                    echo "新金额格式不正确，此字段将保留原值。操作继续。"
                    new_values_array+=("${old_values_array[$i]}")
                    continue
                 fi
            fi
            new_values_array+=("$input_val")
        fi
    done
    new_record_line=$(IFS=,; echo "${new_values_array[*]}")
    awk -F, -v ln="$line_num_to_modify" -v new_line="$new_record_line" \
        'BEGIN{OFS=","} NR==1 {print $0; next} 
        { if (NR == ln) print new_line; else print $0 }' \
        "$EXPENSES_FILE" > "$TEMP_FILE" && mv "$TEMP_FILE" "$EXPENSES_FILE"
    echo "记录修改成功。"
}
query_all_expenses() {
    echo "--- 所有消费记录 ---"
    if [ $(wc -l < "$EXPENSES_FILE") -le 1 ]; then
        echo "账本为空。"
    else
        column -s, -t < "$EXPENSES_FILE" | less -S
    fi
}
stats_by_period_category() {
    echo "--- 按年月进行分类消费统计 ---"
    read -p "请输入要统计的年份 (例如 2024): " year_stat
    read -p "请输入要统计的月份 (1-12, 例如 8 或 08, 留空统计全年): " month_stat
    echo "--- ${year_stat}年 ${month_stat:-[全年]} 按 '${HEADERS[$((MAIN_CAT_COL_NUM-1))]}' 消费统计 ---"
    awk -F, -v y_stat="$year_stat" -v m_stat="$month_stat" \
        -v t_col="$TIME_COL_NUM" -v a_col="$AMOUNT_COL_NUM" -v mc_col="$MAIN_CAT_COL_NUM" \
    'NR > 1 {
        split($t_col, date_parts, "/");
        file_year = date_parts[1];
        file_month = sprintf("%d", date_parts[2]);
        if (file_year == y_stat) {
            if (m_stat == "" || file_month == m_stat) {
                category_sum[$mc_col] += $a_col;
                total_sum += $a_col;
            }
        }
    }
    END {
        printf "%-20s | %s\n", "'"${HEADERS[$((MAIN_CAT_COL_NUM-1))]}"'", "总金额";
        print "---------------------|----------";
        for (cat_item in category_sum) {
            printf "%-20s | %.2f\n", cat_item, category_sum[cat_item];
        }
        print "---------------------|----------";
        if (total_sum > 0) {
            printf "%-20s | %.2f\n", "所选时段总计", total_sum;
        } else {
            print "所选时段无消费记录。";
        }
    }' "$EXPENSES_FILE"
}
sort_by_range() {
    echo "--- 按区间排序显示消费记录 ---"
    echo "1. 按消费金额区间排序"
    echo "2. 按消费时间区间排序"
    read -p "请输入选项: " choice
    if [[ "$choice" -eq 1 ]]; then
        read -p "请输入最小金额: " min_amount
        read -p "请输入最大金额: " max_amount
        if ! [[ "$min_amount" =~ ^[0-9]+(\.[0-9]+)?$ && "$max_amount" =~ ^[0-9]+(\.[0-9]+)?$ ]]; then
            echo "金额格式不正确。"
            return
        fi
        echo "--- 金额在 [$min_amount - $max_amount] 的记录 (按金额降序) ---"
        (head -n 1 "$EXPENSES_FILE" && \
         tail -n +2 "$EXPENSES_FILE" | \
         awk -F, -v a_col="$AMOUNT_COL_NUM" -v min="$min_amount" -v max="$max_amount" \
         '$a_col+0 >= min+0 && $a_col+0 <= max+0 {print $0}' | \
         sort -t',' -k${AMOUNT_COL_NUM},${AMOUNT_COL_NUM}nr) | column -s, -t | less -S
    elif [[ "$choice" -eq 2 ]]; then
        read -p "请输入开始日期 (YYYY/M/D 或 YYYY/MM/DD): " start_date
        read -p "请输入结束日期 (YYYY/M/D 或 YYYY/MM/DD): " end_date
        if ! [[ "$start_date" =~ ^[0-9]{4}/([1-9]|0[1-9]|1[0-2])/([1-9]|0[1-9]|[12][0-9]|3[01])$ && \
                "$end_date" =~ ^[0-9]{4}/([1-9]|0[1-9]|1[0-2])/([1-9]|0[1-9]|[12][0-9]|3[01])$ ]]; then
            echo "日期格式不正确。"
            return
        fi
        echo "--- 时间在 [$start_date - $end_date] 的记录 (按时间降序) ---"
        (head -n 1 "$EXPENSES_FILE" && \
         tail -n +2 "$EXPENSES_FILE" | \
         awk -F, -v t_col="$TIME_COL_NUM" -v start="$start_date" -v end="$end_date" \
         ' $t_col >= start && $t_col <= end {print $0}' | \
         sort -t',' -k${TIME_COL_NUM},${TIME_COL_NUM}r -k${AMOUNT_COL_NUM},${AMOUNT_COL_NUM}nr) | column -s, -t | less -S
    else
        echo "无效选项。"
    fi
}
combined_query() {
    echo "--- 组合查询消费记录 ---"
    read -p "请输入查询日期 (YYYY/M/D, 留空不限): " q_date
    read -p "请输入大分类关键字 (留空不限): " q_main_cat
    read -p "请输入最小金额 (数字, 留空不限): " q_min_amount
    PAYMENT_COL_NUM_QUERY=-1
    for i_q in "${!HEADERS[@]}"; do
        if [[ "${HEADERS[$i_q]}" == "支付方式" ]]; then
            PAYMENT_COL_NUM_QUERY=$((i_q + 1)); break
        fi
    done
    local q_payment=""
    if [ "$PAYMENT_COL_NUM_QUERY" -ne -1 ]; then
      read -p "请输入支付方式关键字 (留空不限): " q_payment
    fi
    echo "--- 组合查询结果 ---"
    (head -n 1 "$EXPENSES_FILE" && \
    awk -F, -v t_col="$TIME_COL_NUM" -v a_col="$AMOUNT_COL_NUM" -v mc_col="$MAIN_CAT_COL_NUM" -v pay_col="$PAYMENT_COL_NUM_QUERY" \
        -v date_f="$q_date" -v cat_f="$q_main_cat" -v amount_f="${q_min_amount:-0}" -v payment_f="$q_payment" \
    'NR > 1 {
        match_date = (date_f == "" || $t_col == date_f);
        match_cat = (cat_f == "" || $mc_col ~ cat_f);
        match_amount = (amount_f == "" || $a_col+0 >= amount_f+0);
        match_payment = (payment_f == "" || (pay_col != -1 && $pay_col ~ payment_f) );
        if (match_date && match_cat && match_amount && match_payment) {
            print $0;
        }
    }' "$EXPENSES_FILE") | column -s, -t | less -S
}
while true; do
    echo -e "\n=============== Shell 记账系统 (作业五) ==============="
    echo "1. 添加消费记录"
    echo "2. 删除消费记录"
    echo "3. 修改消费记录"
    echo "4. 查询所有消费记录 (分页显示)"
    echo "5. 按年月分类统计"
    echo "6. 按金额/时间区间排序显示 (分页显示)"
    echo "7. 组合条件查询 (分页显示)"
    echo "0. 退出系统"
    read -p "请输入你的选择 [0-7]: " choice
    case $choice in
        1) add_expense_info ;;
        2) delete_expense_info ;;
        3) modify_expense_info ;;
        4) query_all_expenses ;;
        5) stats_by_period_category ;;
        6) sort_by_range ;;
        7) combined_query ;;
        0) echo "感谢使用，系统已退出。"; exit 0 ;;
        *) echo "无效输入，请输入0-7之间的数字。" ;;
    esac
    echo ""
    read -n 1 -s -r -p "按任意键返回主菜单..."
    echo ""
done
